package pt.inescid.components.policyengine.heimdall.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import pt.inescid.components.policyengine.heimdall.authorization.AuthorizationAS;
import pt.inescid.components.policyengine.heimdall.base.User;
import pt.inescid.components.policyengine.heimdall.commons.Log;
import pt.inescid.components.policyengine.heimdall.commons.MyServletException;
import pt.inescid.components.policyengine.heimdall.commons.ProjectInfo;
import pt.inescid.components.policyengine.heimdall.database.UserDAO;
import pt.inescid.components.policyengine.heimdall.pap.PolicyManager;

public class PolicyUploadFC extends HttpServlet {

	public void doGet(
					HttpServletRequest request,
					HttpServletResponse response)
			throws IOException, ServletException {

		response.setContentType("text/html");
		response.setDateHeader("Expires", 0);
		response.setHeader("Pragma", "no-cache");

		if (request.getProtocol().equals("HTTP/1.1")) {
			response.setHeader("Cache-Control", "no-cache");
		}

		/* ===========================================================
		==============================================================
		=============                    =============================
		=============      Global variables        ===========
		=============                    =============================
		==============================================================
		=========================================================== */

				String nextURL = null;
				String user = null;
				String token = null;
				String modelTag = null;
				
		/* ===========================================================
		==============================================================
		=============                    =============================
		=============      Read Request Parameters        ===========
		=============                    =============================
		==============================================================
		=========================================================== */
		
//		 Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

//		 Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

//		 Parse the request
		List items = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		 Process the uploaded items
		Iterator iter = items.iterator();
		FileItem policyItem = null;
	    String fieldName = null;
	    
		while (iter.hasNext()) {
		    FileItem item = (FileItem) iter.next();

		    fieldName = item.getFieldName();
		    if (fieldName.equals("user")) {
		    	user = item.getString();
		    }
		    else if (fieldName.equals("token")) {
		    	token = item.getString();
		    }
		    else if (fieldName.equals("modelTag")) {
		    	modelTag = item.getString();
		    }
		    else if (fieldName.equals("policyFile")) {
		    	policyItem = item;
		    }
		}
		    	
		BufferedReader policyReader = 
			new BufferedReader(new InputStreamReader(
					policyItem.getInputStream()));


/* ===========================================================
==============================================================
=============                    =============================
=============      control access          =============================
=============                    =============================
==============================================================
=========================================================== */
		
		Log.debug(Log.DEBUG, "Arrived: " + user + "/" + token, "PolicyUploadFC");
		
		User currentUser = null;
		if (user != null && token != null && 
				AuthorizationAS.isAccessAllowed(Long.parseLong(user), 
						token, "PolicyUploadFC")) {
			currentUser = UserDAO.getRecord(Long.parseLong(user));	
		}
		else {
			throw new MyServletException(MyServletException.ACCESS_DENIED);
		}

/* ===========================================================
==============================================================
=============                    =============================
=============      Begin processing actions        ===========
=============                    =============================
==============================================================
=========================================================== */

		if (modelTag == null) {
			modelTag = currentUser.getNewModelTag();
		}
		
		uploadPolicy(currentUser, modelTag, policyReader, response);
		nextURL = "/" + 
				ProjectInfo.getProperty(
						ProjectInfo.WEBAPP_PROPERTY) + 
					"/policyUpload.jsp?message=Tudo Ok";

/* ===========================================================
==============================================================
=============                    =============================
=============      FINALLY - Redirect    =====================
=============                    =============================
==============================================================
=========================================================== */

		nextURL = nextURL.replace("?", 
				"?user=" + user + "&token=" + token + "&");
		
		Log.debug(Log.DEBUG, "Invoking " + nextURL, "PolicyUploadFC");
		
		response.encodeURL(nextURL);
		response.sendRedirect(nextURL);

	};

	/* ===========================================================
	==============================================================
	=============                    =============================
	=============      uploadPolicy       =====================
	=============                    =============================
	==============================================================
	=========================================================== */
	public void uploadPolicy(User currentUser,
			String userModelTag,
			BufferedReader policyReader, 
			HttpServletResponse response)
	throws IOException, ServletException {
		
		Log.debug(Log.INFO, "Arrived.", "PolicyUploadFC.uploadPolicy"); 	
		
		String currentLine = null;
		String policyText = "";
		while ((currentLine = policyReader.readLine()) != null) {
			policyText += currentLine + "\n";
		}
		
		PolicyManager.storePolicy(currentUser,
				userModelTag,
				policyText);
		
	} // uploadPolicy
	

		
/* ===========================================================
==============================================================
=============                    =============================
=============      doPost       =====================
=============                    =============================
==============================================================
=========================================================== */
	public void doPost(HttpServletRequest request, 
                      HttpServletResponse response)
        throws IOException, ServletException {
       doGet(request, response);
    }
}
